<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>表格操作</title>
		<style type="text/css">
			table{
				border:1px solider;
				margin: auto;
				width: 500px;
			}
			th,td{
				text-align: center;
				border: 1px solid
			}
			div{
				text-align: center;
				margin: 50px;
			}
		</style>
	</head>
	<body>
		<div>
		<input type="text" id="id" value="" placeholder="请输入编号" />
		 <input type="text" id="name" placeholder="请输入姓名" />
		 <input type="text" id="gender" placeholder="请输入性别" />
		 <input type="button"  id="btn_add" value="添加" />
			
		</div>
		 
		 <table >
		 	<caption>学生信息表</caption>
		 	<tr>
		 		<th>编号</th>
		 		<th>姓名</th>
		 		<th>性别</th>
		 		<th>操作</th>	
		 	</tr>
		 	<tr>
		 		<td>1</td>
		 		<td>赵小四</td>
		 		<td>男</td>
		 		<td> <a href="javascript:void(0)" onclick="delTr(this)">删除</a></td>
		 	</tr>
		 </table>
		
		
		<script type="text/javascript">
			//添加
			var btn_add = document.getElementById("btn_add");
			btn_add.onclick=function(){
				//获得文本框内容
				var idt = document.getElementById("id").value;
				var name = document.getElementById("name").value;
				var grade = document.getElementById("gender").value;
				
				//创建td标签并赋值内容
				var td_id = document.createElement("td");	
				var text_id = document.createTextNode(idt);
				td_id.appendChild(text_id);//文本不能直接放入，需要放一个文本节点
				var td_name = document.createElement("td");
				td_name.appendChild(document.createTextNode(name));
				
				var td_grade = document.createElement("td");
				td_grade.appendChild(document.createTextNode(grade));
				
				//创建a标签td
				var td_a = document.createElement("td");
				var ele_a = document.createElement("a");
				ele_a.setAttribute("href","javascript:void(0);");
				ele_a.setAttribute("onclick","delTr(this);");
				var text_a = document.createTextNode("删除");
				ele_a.appendChild(text_a);
				td_a.appendChild(ele_a);
				
				//创建tr,将Td添加进去
				var tr_r = document.createElement("tr");
				
				tr_r.appendChild(td_id);
				tr_r.appendChild(td_name);
				tr_r.appendChild(td_grade);
				tr_r.appendChild(td_a);
				
				//tr添加到table中
				var tab = document.getElementsByTagName("table")[0];
				tab.appendChild(tr_r);
			}
			//删除功能
			/**
			 * 1:确定删除的是哪个超连接
			 * 
			 * 2：删除当前对象
			 */
			
			function delTr(obj){
				var table = obj.parentNode.parentNode.parentNode;
				var tr = obj.parentNode.parentNode;
				table.removeChild(tr);
				
			}
		</script>
	</body>
</html>
